﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.Entity;
using Seven.DataModel.ViewModels.WorkflowAbout;
using Seven.Tools.Extension;

namespace Seven.MsSql.Repositories
{
    public partial class WfFormTypeRepository
    {
        /// <summary>
        /// 根据表单类别ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">表单类别ID</param>
        /// <returns></returns>
        public FormTypeModel GetEditModelByID(int id)
        {
            var type = this.Entities().Where(w => w.ID == id);
            var company = new HrOrganizationRepository(this.dbContext).Entities();

            var query = from a in type
                        join b in company on a.CompanyID equals b.ID into ab
                        from CompanyInfo in ab.DefaultIfEmpty()
                        select new
                        {
                            a.ID,
                            a.Name,
                            a.SortNumber,
                            a.ParentID,
                            a.CompanyID,
                            CompanyName = CompanyInfo == null ? "" : CompanyInfo.Name,
                            a.Remark
                        };

            var data = query.FirstOrDefault();

            return data.CastTo<FormTypeModel>();
        }

        /// <summary>
        /// 根据表单类别ID获取其类别名称
        /// </summary>
        /// <param name="id">表单类别ID</param>
        /// <returns></returns>
        public string GetFormTypeName(int id)
        {
            return this.Entities().Where(w => w.ID == id).Select(s => s.Name).FirstOrDefault();
        }

        /// <summary>
        /// 根据父级ID获取下一级表单类型集合
        /// </summary>
        /// <param name="id">父级id</param>
        /// <returns></returns>
        public IEnumerable<WfFormType> GetSons(int id)
        {
            return this.Entities().Where(w => w.ParentID == id).OrderBy(o => o.SortNumber).ToArray();
        }

        /// <summary>
        /// 根据表单类型ID集合，获取他们的下一级表单类型的数量，以Dic形式返回数据，其中Key为ids的元素，Value为其下一级表单类型数量
        /// </summary>
        /// <param name="ids">表单类型ID集合</param>
        /// <returns></returns>
        public IDictionary<int, int> GetSonsCount(IEnumerable<int> ids)
        {
            var result = new Dictionary<int, int>();
            if (ids.Count() == 0) { return result; }

            var data = this.Entities().Where(w => ids.Contains(w.ParentID)).GroupBy(g => g.ParentID).Select(s => new { s.Key, Value = s.Count() });
            foreach (var item in data)
            {
                result.Add(item.Key, item.Value);
            }

            return result;
        }

        /// <summary>
        /// 根据表单类型ID判定其是否存在子集类型
        /// </summary>
        /// <param name="id">表单类型ID</param>
        /// <returns></returns>
        public bool SonExist(int id)
        {
            return this.Any(a => a.ParentID == id);
        }
    }
}
